package com.study.system.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.common.entity.User;
import com.study.system.user.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 自定义用户验证的逻辑
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //按用户名查询用户
        User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username));
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //包装用户信息，返回给security
        org.springframework.security.core.userdetails.User user1 =
                new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),
                        AuthorityUtils.commaSeparatedStringToAuthorityList(""));
        return user1;
    }
}
